package com.jxb.netty.rocketmqNetty;

import com.jxb.netty.network.netty.nettyadv.NettyServer;
import com.jxb.netty.network.netty.nettyadv.server.ServerInit;
import com.jxb.netty.network.netty.nettyadv.vo.NettyConstant;
import com.jxb.netty.rocketmqNetty.handler.NettyConnectManageHandler;
import com.jxb.netty.rocketmqNetty.handler.NettyServerHandler;
import com.jxb.netty.rocketmqNetty.serializable.RockEncode;
import com.jxb.netty.rocketmqNetty.serializable.RocketDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.redis.RedisDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.NettyRuntime;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

public class RocketNettyServer {

    private static final Logger LOG = LoggerFactory.getLogger(RocketNettyServer.class);

    public static void main(String[] args) throws InterruptedException {
        new RocketNettyServer().bind();
    }

    private void bind() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1,new DefaultThreadFactory("boss"));
        EventLoopGroup workerGroup = new NioEventLoopGroup(NettyRuntime.availableProcessors(),
                new DefaultThreadFactory("nt_worker"));
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.SO_REUSEADDR,true)
                .option(ChannelOption.SO_KEEPALIVE,false)
                .option(ChannelOption.TCP_NODELAY,true)
                .childOption(ChannelOption.SO_SNDBUF,65535)
                .childOption(ChannelOption.SO_RCVBUF,65535)
                .localAddress(new InetSocketAddress(6879))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new RockEncode())
                                .addLast(new RocketDecoder())
                                .addLast(new IdleStateHandler(0,0,120))
                                .addLast(new NettyConnectManageHandler())
                                .addLast(new NettyServerHandler());
                    }
                });
        // 绑定端口，同步等待成功
        b.bind(NettyConstant.SERVER_PORT).sync();
        LOG.info("Netty server start : "
                + (NettyConstant.SERVER_IP + " : "
                + NettyConstant.SERVER_PORT));
    }
}
